package com.paipai.helper.service;


import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.paipai.helper.R;
import com.paipai.helper.util.CmdUtil;
import com.paipai.helper.util.SPConstant;
import com.paipai.helper.util.ViewIdConstant;
import com.yhao.floatwindow.FloatWindow;
import com.yhao.floatwindow.MoveType;
import com.yhao.floatwindow.PermissionListener;
import com.yhao.floatwindow.Screen;
import com.yhao.floatwindow.ViewStateListener;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.paipai.helper.util.SPConstant.SP_COLLECT_X;
import static com.paipai.helper.util.SPConstant.SP_COLLECT_Y;
import static com.paipai.helper.util.SPConstant.SP_SEED_COUNT;
import static com.paipai.helper.util.SPConstant.SP_SEED_X;
import static com.paipai.helper.util.SPConstant.SP_SEED_Y;
import static com.paipai.helper.util.ViewIdConstant.VIEW_ID_GET_MONEY;
import static com.paipai.helper.util.ViewIdConstant.VIEW_ID_PACKAGE_FULL_CLOSE;
import static com.paipai.helper.util.ViewIdConstant.VIEW_ID_SEED;
import static com.paipai.helper.util.ViewIdConstant.VIEW_ID_SEED_INTRO;
import static com.paipai.helper.util.ViewIdConstant.VIEW_ID_SHARE_CLOSE;

/**
 * 类描述：
 * <p>
 * 作者：TB.Liu on 19-3-12 15:48
 */
public class UIHelperService extends AccessibilityService  implements View.OnClickListener{
    private FloatWindow.B mFloatWindow;
    boolean isBlock = true;
    private int mClickTempX;
    private int mClickTempY;
    boolean isBegin = false;
    boolean isExecuting = false;
    boolean hasCheckSeed = false;
    boolean isPause = true;
    private TextView mInfoTv;
    private LinearLayout mConfigView;

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        //除了xml配置文件，还可以在这里初始化配置
        AccessibilityServiceInfo serviceInfo = getServiceInfo();
        serviceInfo.flags |= AccessibilityServiceInfo.FLAG_REQUEST_ENHANCED_WEB_ACCESSIBILITY;
        // 响应事件的类型，这里是全部的响应事件（长按，单击，滑动等）
        serviceInfo.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;

        // 反馈给用户的类型，这里是语音提示
        //serviceInfo.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN;
        // 过滤的包名
//        List<String> packages = MyApplication.appPackageInfos;
//        //可以设置多个监听应用，不设置默认监听全部应用
        String[] array = new String[]{"com.ifreetalk.ftalk"};
        serviceInfo.packageNames = array;
        setServiceInfo(serviceInfo);
        Log.d("FloationView", "onServiceConnected");
        initView();
    }

    @Override
    public void onInterrupt() {
        Log.d("FloationView", "onInterrupt");
    }

    @Override
    public List<AccessibilityWindowInfo> getWindows() {
        Log.d("FloationView", "getWindows");
        return super.getWindows();
    }

    @Override
    public AccessibilityNodeInfo getRootInActiveWindow() {
        return super.getRootInActiveWindow();
    }


    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if(isPause){
            return;
        }
        AccessibilityNodeInfo nodeInfo =  event.getSource();
        if(nodeInfo != null){
//            Log.d("FloationView", "当前被点击的View为："+nodeInfo.getText()+" 包名："+event.getPackageName().toString());
        }
        if(isBegin){
            if(!isExecuting){
                isExecuting = true;
                hasCheckSeed = false;
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //收取
                Log.d("FloationView", "有收取界面");
                executeViewClick(ViewIdConstant.VIEW_ID_COLLECT);
                executeViewClick(VIEW_ID_SHARE_CLOSE);
                executeViewClick(VIEW_ID_GET_MONEY);
                executeViewClick(VIEW_ID_PACKAGE_FULL_CLOSE);
                //开始种植
                while (!checkViewIsShow(VIEW_ID_SEED)){//检查种子控件是否在当前界面上
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    CmdUtil.callBack();
                    if(checkViewIsShow(VIEW_ID_SEED)){
                        break;
                    }
                }
                boolean seedSuccess = executeViewClick(VIEW_ID_SEED);
                Log.d("FloationView", "种植按钮点击成功："+seedSuccess);

                if(seedSuccess){
                    try {
                        Thread.sleep(800);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    CmdUtil.seedTypeClick(this);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    int count = SPConstant.getIntDataFromCacheByKey(this, SP_SEED_COUNT);
                    Log.d("FloationView", "种子数量= "+count);
                    try {
                        for(int i=0; i< count; i++){
                            Thread.sleep(100);
                            CmdUtil.seedClick(this);

                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    executeViewClick(VIEW_ID_SEED_INTRO);
                    isBegin = false;
                    isExecuting = false;
                }
            }


        } else {
            if(!isExecuting){
                isBegin = checkIsCanBegin();
                executeViewClick(ViewIdConstant.VIEW_ID_COLLECT);
                executeViewClick(VIEW_ID_SHARE_CLOSE);
                executeViewClick(VIEW_ID_GET_MONEY);
                executeViewClick(VIEW_ID_PACKAGE_FULL_CLOSE);
                if(checkViewIsShow(VIEW_ID_SEED) && !hasCheckSeed){
                    boolean seedSuccess = executeViewClick(VIEW_ID_SEED);
                    Log.d("FloationView", "种植按钮点击成功："+seedSuccess);
                    if(seedSuccess){
                        try {
                            Thread.sleep(800);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        CmdUtil.seedTypeClick(this);
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        int count = SPConstant.getIntDataFromCacheByKey(this, SP_SEED_COUNT);
                        Log.d("FloationView", "种子数量= "+count);
                        try {
                            for(int i=0; i< count; i++){
                                Thread.sleep(100);
                                CmdUtil.seedClick(this);
                                if(checkViewIsShow(VIEW_ID_SEED_INTRO)){
                                    hasCheckSeed = true;
                                    break;
                                }

                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                executeViewClick(VIEW_ID_SEED_INTRO);
            }
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_helper_start:
                isPause = false;
                startCollect();
                break;
            case R.id.btn_helper_pause:
                isPause = true;
                break;
            case R.id.btn_save_position://收取
                Toast.makeText(this, "保存收取位置", Toast.LENGTH_SHORT).show();
                Map<String, Object> collect = new HashMap<>();
                collect.put(SP_COLLECT_X, mClickTempX);
                collect.put(SP_COLLECT_Y, mClickTempY);
                SPConstant.saveDataToCache(this, collect);
                break;
            case R.id.btn_save_seed_position:
                Toast.makeText(this, "保存种植位置", Toast.LENGTH_SHORT).show();
                Map<String, Object> seed = new HashMap<>();
                seed.put(SP_SEED_X, mClickTempX);
                seed.put(SP_SEED_Y, mClickTempY);
                SPConstant.saveDataToCache(this, seed);
                break;
            case R.id.view_config:
                int visible = View.VISIBLE;
                int moveType =  MoveType.active;
                if(mConfigView.getVisibility() == View.VISIBLE){
                    moveType = MoveType.slide;
                    visible = View.GONE;
                }
                mConfigView.setVisibility(visible);
                mFloatWindow.setMoveType(moveType);
                break;
            case R.id.btn_exit:
                FloatWindow.destroy();
                this.stopSelf();
                break;
            default:
                break;
        }
    }

    /**
     * 使用系统级别的WindowManager展示悬浮框，需要6.0以上的权限；
     */
    private void initView() {
        View view = LayoutInflater.from(this).inflate(R.layout.widget_chathead,null);
        view.findViewById(R.id.btn_helper_start).setOnClickListener(this);
        view.findViewById(R.id.btn_save_position).setOnClickListener(this);
        view.findViewById(R.id.btn_save_seed_position).setOnClickListener(this);
        view.findViewById(R.id.view_config).setOnClickListener(this);
        view.findViewById(R.id.btn_helper_pause).setOnClickListener(this);
        view.findViewById(R.id.btn_exit).setOnClickListener(this);
        mConfigView = (LinearLayout)view.findViewById(R.id.layout_operation);
        mInfoTv = (TextView)view.findViewById(R.id.btn_position_info);
        mFloatWindow = FloatWindow
                .with(getApplicationContext())
                .setView(view)
//                .setWidth(100)                               //设置控件宽高
//                .setHeight(Screen.height,0.2f)
                .setX(100)                                   //设置控件初始位置
                .setY(Screen.height,0.3f)
                .setDesktopShow(true)                        //桌面显示
                .setMoveType(MoveType.active);
        mFloatWindow.setViewStateListener(new ViewStateListener() {
            @Override
            public void onPositionUpdate(int i, int i1) {
                mClickTempX = i;
                mClickTempY = i1;
            }

            @Override
            public void onShow() {

            }

            @Override
            public void onHide() {

            }

            @Override
            public void onDismiss() {

            }

            @Override
            public void onMoveAnimStart() {

            }

            @Override
            public void onMoveAnimEnd() {
            }

            @Override
            public void onBackToDesktop() {

            }
        })
                .setPermissionListener(new PermissionListener() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onFail() {

                    }
                })
                .build();
        FloatWindow.get().show();
    }

    private boolean executeViewClick(String viewId){
        AccessibilityNodeInfo root = this.getRootInActiveWindow();
        if(root != null){
            List<AccessibilityNodeInfo> nodes = root.findAccessibilityNodeInfosByViewId(viewId);
            if(nodes != null){
                String cmdInfo = ViewIdConstant.cmdMapInfo.get(viewId);
                Log.d("FloationView", cmdInfo+"信息数量"+ nodes.size());
                if(nodes.size()>0){
                    Log.d("FloationView", "执行"+cmdInfo+"的点击事件");
                    return nodes.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
            }
        }
        return false;
    }

    private void executeHideView(String viewId){
        AccessibilityNodeInfo root = this.getRootInActiveWindow();
        if(root != null){
            List<AccessibilityNodeInfo> nodes = root.findAccessibilityNodeInfosByViewId(viewId);
            if(nodes != null){
                String cmdInfo = ViewIdConstant.cmdMapInfo.get(viewId);
                Log.d("FloationView", cmdInfo+"信息数量"+ nodes.size());
                if(nodes.size()>0){
                    Log.d("FloationView", "执行"+cmdInfo+"的隐藏事件");
                    nodes.get(0).setVisibleToUser(false);
                }

            }
        }
    }

    private boolean switchTab(String viewId){
        AccessibilityNodeInfo root = this.getRootInActiveWindow();
        if(root != null){
            List<AccessibilityNodeInfo> nodes = root.findAccessibilityNodeInfosByViewId(viewId);
            if(nodes != null){
                String cmdInfo = ViewIdConstant.cmdMapInfo.get(viewId);
                int size = nodes.size();
                Log.d("FloationView", cmdInfo+"信息数量"+ nodes.size());
                if(nodes.size()>3){
                    //切换tab，使种菜界面恢复初始化状态
                    boolean result = false;
                    try {
                        result = nodes.get(1).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        Log.d("FloationView", "执行"+cmdInfo+nodes.get(1).getText()+"的点击事件");
                        Thread.sleep(1000);
                        result = nodes.get(2).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        Log.d("FloationView", "执行"+cmdInfo+nodes.get(2).getText()+"的点击事件");
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    return result;
                }

            }
        }
        return false;
    }

    private boolean checkIsCanBegin(){
        AccessibilityNodeInfo root = this.getRootInActiveWindow();
        if(root != null){
            String viewId = ViewIdConstant.VIEW_ID_COLLECT;
            List<AccessibilityNodeInfo> nodes = root.findAccessibilityNodeInfosByViewId(viewId);
            if(nodes != null){
                String cmdInfo = ViewIdConstant.cmdMapInfo.get(viewId);
                if(nodes.size()>0){
                    Log.d("FloationView", "显示收取界面，可以开始");
                    return true;
                }

            }
        }
        return false;
    }

    private boolean checkViewIsShow(String viewId){
        AccessibilityNodeInfo root = this.getRootInActiveWindow();
        boolean result = false;
        if(root != null){
            List<AccessibilityNodeInfo> nodes = root.findAccessibilityNodeInfosByViewId(viewId);
            if(nodes != null){

                if(nodes.size()>0){
                    result = true;
                }

            }
        }
        String cmdInfo = ViewIdConstant.cmdMapInfo.get(viewId);
        Log.d("FloationView", cmdInfo+"是否在当前界面："+result);
        return result;
    }



    /**
     * 开始收菜
     */
    private void startCollect(){
        CmdUtil.collectClick(this);
        Toast.makeText(this, "管家开启成功", Toast.LENGTH_SHORT).show();
    }

    private void startCountDown(){
        long time = SPConstant.getLongDataFromCacheByKey(this, SPConstant.SP_COUNT_DOWN);
        final SimpleDateFormat sp = new SimpleDateFormat(" HH:mm:ss");
        CountDownTimer timer = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Date date = new Date(millisUntilFinished);
                mInfoTv.setText("还剩"+ sp.format(date).toString());
            }

            @Override
            public void onFinish() {
                startCollect();
            }
        };
        timer.start();
        Log.d("FloationView", "倒计时开始"+time);
    }

}

